<template>
  <div class="yd-collapse-item">
    <div class="collapse-item-header" @click="handleExpanded">
      <div class="collapse-item-title">
        <span v-if="title">{{title}}</span>
        <slot v-else name="title"></slot>
      </div>
      <div :class="['collapse-item-icon',expand?'is-active':'']">&gt;</div>
    </div>
    <div class="collapse-item-body" :style="`height:${height}px`">
      <div class="collapse-item-content" ref="expandContent">
        <slot></slot>
      </div>
    </div>
  </div>
</template>

<script>
import { ref, getCurrentInstance, onMounted, inject, watch } from "vue";
export default {
  name: "CollapseItem",
  props: {
    name: String,
    title: String
  },
  setup(props, ctx) {
    // const accordion = inject("accordion");
    let height = ref(0);
    let expand = ref(false);
    const expandContent = ref(null);
    const instance = getCurrentInstance();

    const initExpand = () => {
      const parentModel = instance.parent.ctx.parentModel;
      if (parentModel.includes(props.name)) {
        expand.value = true;
        height.value = expandContent.value.clientHeight;
      } else {
        expand.value = false;
        height.value = 0;
      }
    };

    const handleExpanded = () => {
      instance.parent.ctx.handleUpdate(props.name, !expand.value);
    };

    onMounted(() => {
      initExpand();
    });

    watch(
      () => instance.parent.ctx.parentModel,
      val => {
        initExpand();
      }
    );

    return {
      height,
      expand,
      expandContent,

      initExpand,
      handleExpanded
    };
  }
};
</script>

<style lang="scss" scoped>
.yd-collapse-item {
  width: 100%;
  box-sizing: border-box;
  border-bottom: 1px solid #ebeef5;
  .collapse-item-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 20px 0;
    cursor: pointer;
    .collapse-item-icon {
      font-weight: bold;
      transform: rotate(0);
      transition: all 0.5s;
    }
    .is-active {
      transform: rotate(90deg);
    }
  }
  .collapse-item-body {
    overflow: hidden;
    box-sizing: border-box;
    height: 0;
    transition: height 0.5s;
    .collapse-item-content {
      padding-bottom: 20px;
    }
  }
}
</style>